package com.bysj.lms.utils;


import com.bysj.lms.properties.UploadProperties;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Component
public class UploadUtil {

    @Resource
    private UploadProperties uploadPropertiesAutowired;

    private static UploadProperties uploadProperties;

    /**
     * 当DI容器实例化当前受管Bean时，@PostConstruct注解的方法会被自动出发，从而完成一些初始化工作
     * 只有一个方法可以使用该注解
     * 被注解方法不得有任何参数
     * 被注解方法不得抛出已检查异常
     * 被注解方法需是非静态方法
     * 此方法只会被执行一次
     */
    @PostConstruct
    public void init(){
        uploadProperties = this.uploadPropertiesAutowired;
    }

    public static String getPath(){
        return uploadProperties.getPath();
    }

    public static String upload(MultipartFile multipartFile,String path){
        System.out.println(path);
        File file = new File(path);
        String imgname = null;
        if(multipartFile != null){
            if(!file.exists()){
                file.mkdirs();
            }
            UUID uuid = UUID.randomUUID();
            String[] suffix = multipartFile.getOriginalFilename().split("\\.");
            imgname = uuid+"."+suffix[1];
            file = new File(path + imgname);
            try {
                multipartFile.transferTo(file);
                return imgname;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return imgname;
    }

}
